package com.demo.controller;

import com.demo.pojo.ResultVO;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/ai/context")
public class ChatContextController {

    private final ChatClient chatClient;

    public ChatContextController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }
    @GetMapping("/chat/{message}")
    public ResultVO<String> chat(@PathVariable String message, HttpSession session) {
        log.info("用户消息: {}", message);

        // 从session中获取对话历史，如果没有则创建新的
        List<Message> conversationHistory = getOrCreateHistory(session);

        // 添加用户的新消息到历史记录
        conversationHistory.add(new UserMessage(message));

        // 调用AI，传入完整的对话历史
        String response = chatClient.prompt()
                .messages(conversationHistory) // 传入所有历史消息
                .call()
                .content();

        // 添加AI的回复到历史记录
        conversationHistory.add(new AssistantMessage(response));

        // 限制历史记录长度，避免token过多
        if (conversationHistory.size() > 10) {
            // 保留系统消息和最近的对话
            Message systemMessage = conversationHistory.get(0);
            List<Message> recentMessages = conversationHistory.subList(
                    conversationHistory.size() - 9, conversationHistory.size());

            conversationHistory = new ArrayList<>();
            conversationHistory.add(systemMessage);
            conversationHistory.addAll(recentMessages);
            session.setAttribute("conversationHistory", conversationHistory);
        }

        log.info("AI回复: {}", response);
        return ResultVO.success(response);
    }

    /**
     * 清空对话历史
     */
    @GetMapping("/clear")
    public ResultVO<String> clearHistory(HttpSession session) {
        session.removeAttribute("conversationHistory");
        return ResultVO.success();
    }

    /**
     * 获取或创建对话历史
     */
    private List<Message>getOrCreateHistory(HttpSession session) {
        List<Message> history =
                (List<Message>) session.getAttribute("conversationHistory");
        if (history == null) {
            history = new ArrayList<>();
            // 添加系统提示词来引导AI行为
            history.add(new SystemMessage("你是一个智慧办公系统，可以帮助用户"));
            session.setAttribute("conversationHistory", history);
        }
        return history;
    }
}